package com.kingdee.pda.ui.out_check;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.basecommon.utils.PreferencesUtils;
import com.example.basecommon.utils.SpeakUtils;
import com.example.basecommon.view.MoveDragButton;
import com.kingdee.pda.R;
import com.kingdee.pda.entity.OutCheckRequestBean;
import com.kingdee.pda.entity.ScanOutOrderInfoBean;
import com.kingdee.pda.entity.ScanOutOrderInfoBean.StockOutOrderDetailInfosBean;
import com.kingdee.pda.entity.ScanSnResponsebean;
import com.kingdee.pda.entity.SnlistBean;
import com.kingdee.pda.entity.Warehouse;
import com.kingdee.pda.ui.activity.BaseTitleActivity;
import com.kingdee.pda.util.CommonUtil;
import com.kingdee.pda.util.ConstantPreference;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Set;

/**
 * 出库复核
 * Created by dlj
 * DATE 2021/9/15
 * TIME 15:20
 */
public class OutCheckActivity extends BaseTitleActivity implements View.OnKeyListener, OutCheckContract.IOutCheckView {
    private LinearLayout ll_snCode, ll_specialCode;
    private EditText et_orderNo, et_skuCode, et_snCode, et_specialCode;
    private TextView tv_hasCheck, tv_skuNum, tv_waitCheck, tv_des, tv_orderNum;
    private Button btn_confirm;
    private RecyclerView recyclerView;
    private MoveDragButton floatbutton;
    private OutCheckListAdapter adapter;
    private List<StockOutOrderDetailInfosBean> lists = new ArrayList<>();
    private OutCheckPresenter presenter;
    private ScanOutOrderInfoBean orderInfoBean;
    private boolean autoSn;//仓库是否开启SN
    private boolean isOpenMidSn;//pda是否开启半程sn
    private boolean qrcode_isopen;
    private boolean isMidSnScan = false;//正常唯一码和半程唯一码都需要调用sn查询，所以加一个标识，标识是谁发起的
    private String skuCode;
    private int orderNum = 0;
    private StockOutOrderDetailInfosBean selectDetailInfosBean;
    private int selectDetailInfosBeanIndex;

    public static void actionStart(Context context) {
        context.startActivity(new Intent(context, OutCheckActivity.class));
    }

    @Override
    protected void onActivityCreate(Bundle savedInstanceState) {
        super.onActivityCreate(savedInstanceState);
        setContentView(R.layout.activity_out_check);
    }

    @Override
    protected void initView() {
        super.initView();
        setTitle("出库复核");
        tv_des = findViewById(R.id.tv_des);
        floatbutton = findViewById(R.id.floatbutton);

        ll_snCode = findViewById(R.id.ll_snCode);
        ll_specialCode = findViewById(R.id.ll_specialCode);

        et_orderNo = findViewById(R.id.et_orderNo);
        et_specialCode = findViewById(R.id.et_specialCode);
        et_skuCode = findViewById(R.id.et_skuCode);
        et_snCode = findViewById(R.id.et_snCode);
        setEditTextScannerEvents(et_orderNo, this);
        setEditTextScannerEvents(et_specialCode, this);
        setEditTextScannerEvents(et_skuCode, this);
        setEditTextScannerEvents(et_snCode, this);

        tv_hasCheck = findViewById(R.id.tv_hasCheck);
        tv_skuNum = findViewById(R.id.tv_skuTypes);
        tv_waitCheck = findViewById(R.id.tv_waitCheck);
        tv_orderNum = findViewById(R.id.tv_orderNum);

        recyclerView = findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new OutCheckListAdapter(this, lists);
        recyclerView.setAdapter(adapter);

        btn_confirm = findViewById(R.id.btn_confirm);
        btn_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                outcheckConfirm();
            }
        });

        floatbutton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                List<SnlistBean> data = new ArrayList<>();
                for (StockOutOrderDetailInfosBean bean : lists) {
                    data.addAll(bean.getSnlist());
                }

                //进行排序
                Collections.sort(data, new Comparator<SnlistBean>() {
                    public int compare(SnlistBean e1, SnlistBean e2) {
                        int a = e1.getSkuCode().compareTo(e2.getSkuCode());
                        return a;
                    }
                });
                SnListActivity.actionStart(OutCheckActivity.this, data);
            }
        });

        autoSn = PreferencesUtils.getBoolean(this, ConstantPreference.AUTO_SN);
        isOpenMidSn = PreferencesUtils.getBoolean(this, ConstantPreference.MID_SN_IS_OPEN);
        qrcode_isopen = PreferencesUtils.getBoolean(this, ConstantPreference.QRCODE_IS_OPEN);

//        if (isOpenMidSn) {
//            adapter.setAutoSn(true);
//            ll_snCode.setVisibility(View.VISIBLE);
//        } else if (autoSn) {
//            tv_des.setText("商品条码/序列号");
//            et_skuCode.setHint("请扫描/输入商品条码/序列号");
//            adapter.setAutoSn(true);
//        }
        adapter.setAutoSn(true);

        //显示特殊码扫描框
        if (qrcode_isopen) {
            ll_specialCode.setVisibility(View.VISIBLE);
        }

        presenter = new OutCheckPresenter(this, this);
    }

    private void outcheckConfirm() {
        if (orderInfoBean != null && lists.size() > 0) {
            //拼接参数上传
            OutCheckRequestBean outCheckRequestBean = new OutCheckRequestBean();
            outCheckRequestBean.setId(orderInfoBean.getId());
            List<OutCheckRequestBean.DetailBean> detailBeans = new ArrayList<>();
            for (StockOutOrderDetailInfosBean bean : lists) {
                OutCheckRequestBean.DetailBean detail = new OutCheckRequestBean.DetailBean();
                detail.setDetailid(bean.getDetailId());
                detail.setSkuid(bean.getSku());
                detail.setScannedqty(bean.getScannedqty() + "");
                detail.setSeq(bean.getLineno());
                detail.setSnlist(new ArrayList<>(bean.getSnlist()));

                detailBeans.add(detail);
            }
            outCheckRequestBean.setDetail(detailBeans);
            outCheckRequestBean.setHalfWayCodeStatus(isOpenMidSn);
            presenter.confirmStockOutReview(outCheckRequestBean);
        }
    }

    @Override
    protected void initData() {
        super.initData();
    }

    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if (!(v instanceof EditText)) {
            return false;
        }
        EditText editText = (EditText) v;
        String input = editText.getText().toString().trim();
        if (TextUtils.isEmpty(input)) return false;
        if ((keyCode == KeyEvent.KEYCODE_SYSRQ || keyCode == KeyEvent.KEYCODE_ENTER) && event.getAction() == KeyEvent.ACTION_UP) {
            switch (v.getId()) {
                case R.id.et_orderNo:
                    presenter.reviewStockOutBillOrExpressNo(input);
                    if (qrcode_isopen) {
                        CommonUtil.requestFocusAndClearText(et_specialCode);
                    } else {
                        CommonUtil.requestFocusAndClearText(et_skuCode);
                    }
                    break;
                case R.id.et_specialCode:
                    //扫描特殊码后，自动填充条码/半程唯一码
                    String qrSkuCode = CommonUtil.getQRSkuCode(this, input);
                    String qrSnCode = CommonUtil.getQRSnCode(this, input);
                    if (TextUtils.isEmpty(qrSkuCode) || TextUtils.isEmpty(qrSnCode)) {
                        SpeakUtils.speakWithToast(OutCheckActivity.this, "解析特殊码有误，请检查配置", true, false);
                        CommonUtil.requestFocusAndNoClearText(et_specialCode);
                        return false;
                    }
                    et_skuCode.setText(qrSkuCode);
                    et_snCode.setText(qrSnCode);
                    et_skuCode.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_ENTER));

                    break;
                case R.id.et_skuCode:
                    if (orderInfoBean == null || TextUtils.isEmpty(et_orderNo.getText().toString())) {
                        SpeakUtils.speakWithToast(OutCheckActivity.this, "请先扫描出库/物流单号并确认", true, false);
                        CommonUtil.requestFocusAndNoClearText(et_orderNo);
                        return false;
                    }

                    String skuSplit = CommonUtil.skuCodeSplit(OutCheckActivity.this, input);
                    if (TextUtils.isEmpty(skuSplit)) {
//                        if (autoSn && !isOpenMidSn) {//如果截取出了问题并且没有开启半程唯一码，则调用查询sn接口
//                            isMidSnScan = false;
                        presenter.pdaSnScan(input);
//                        } else {
//                            SpeakUtils.speakWithToast(OutCheckActivity.this, "商品条码截取结果为空，请检查输入和截图规则", false, false);
//                            scanSkuOrQrFinished();
//                        }
                        return false;
                    }

                    selectDetailInfosBean = null;
                    selectDetailInfosBeanIndex = 0;
                    // 匹配条码
                    for (int i = 0; i < lists.size(); i++) {
                        StockOutOrderDetailInfosBean bean = lists.get(i);
                        if (bean.getSkubarcode().contains(skuSplit)) {
                            selectDetailInfosBean = bean;
                            selectDetailInfosBeanIndex = i;
                            if (bean.getScannedqty() < bean.getQty()) {
                                break;
                            }
                        }
                    }

                    if (selectDetailInfosBean != null) {
                        switch (getSnType(selectDetailInfosBean)) {
                            case "ALL":
                                SpeakUtils.speakWithToast(OutCheckActivity.this, "请扫描序列号！", true, false);
                                CommonUtil.requestFocusAndClearText(et_skuCode);
                                return true;
                            case "HALF":
                                if ("销售出库".equals(orderInfoBean.getOuttype()) || "B2B出库".equals(orderInfoBean.getOuttype())) {
                                    et_snCode.setEnabled(true);
                                    CommonUtil.requestFocusAndClearText(et_snCode);
                                    return true;
                                }
                                break;
                            case "OFF":
                                break;
                            default:
                                SpeakUtils.speakWithToast(OutCheckActivity.this, "类型不存在！", true, false);
                                CommonUtil.requestFocusAndClearText(et_skuCode);
                                return true;
                        }

                        //如果该商品没开启SN，且扫描匹配通过，继续判断数量能否继续复核
                        addNum(selectDetailInfosBean, selectDetailInfosBeanIndex);
                        return true;
                    }

                    if (qrcode_isopen) {
                        SpeakUtils.speakWithToast(OutCheckActivity.this, "商品不属于该出库单！", true, false);
                        scanSkuOrQrFinished();
                        return true;
                    } else if (autoSn && !isOpenMidSn) {//如果条码不存在并且仓库开启sn，调用sn码接口查询是否sn
                        if (input.length() >= 22 && lists.size() > 0 && "广东好太太科技集团股份有限公司".equals(lists.get(0).getOwnername())) {  //好太太需要截取22位
                            input = input.substring(0, 22);
                        }
                        isMidSnScan = false;
                        presenter.pdaSnScan(input);
                    } else {
                        SpeakUtils.speakWithToast(OutCheckActivity.this, "商品不属于该出库单！", true, false);
                        CommonUtil.requestFocusAndClearText(et_skuCode);
                    }

                    break;

                case R.id.et_snCode:
                    if (orderInfoBean == null || TextUtils.isEmpty(et_orderNo.getText().toString())) {
                        SpeakUtils.speakWithToast(OutCheckActivity.this, "请先扫描出库/物流单号并确认", true, false);
                        CommonUtil.requestFocusAndNoClearText(et_orderNo);
                        return false;
                    }
                    skuCode = et_skuCode.getText().toString();
                    if (TextUtils.isEmpty(skuCode)) {
                        SpeakUtils.speakWithToast(OutCheckActivity.this, "请先扫描/输入商品条码并确认", true, false);
                        CommonUtil.requestFocusAndNoClearText(et_skuCode);
                        return false;
                    }

                    presenter.pdaCollectNullSn(input);

//                    isMidSnScan = true;
//                    presenter.pdaSnScan(input);

                    break;
            }
        }
        return false;
    }

    private String getSnType(StockOutOrderDetailInfosBean detailInfosBean) {
        switch (detailInfosBean.getSnOutType()) {
            case "0":
                return "OFF";
            case "1":
                return "ALL";
            case "2":
                return "HALF";
            default:
                return "";
        }
    }

    private void addNum(StockOutOrderDetailInfosBean detailInfosBean, int index) {
        if (detailInfosBean.getScannedqty() != detailInfosBean.getQty()) {
            SpeakUtils.onlyRing(this, 2);
            detailInfosBean.setScannedqty(detailInfosBean.getScannedqty() + 1);
            adapter.setOpinionPosition(index);
            adapter.notifyDataSetChanged();
            CommonUtil.requestFocusAndClearText(et_skuCode);
            reflushTextView();
        } else {
            SpeakUtils.speakWithToast(OutCheckActivity.this, "商品已扫描数量不可超过该商品总数！", true, false);
        }
    }

    @Override
    public void reviewStockOutBillOrExpressNoSuccess(ScanOutOrderInfoBean orderInfoBean) {
        SpeakUtils.onlyRing(this, 2);
//        if (TextUtils.equals(getCurrentWarehouse().getId(), orderInfoBean.getWarehouseId())) {

        if (getCurrentWarehouse().getId() != orderInfoBean.getWarehouseId()) {
            SpeakUtils.speakWithToast(OutCheckActivity.this, "此单不属于该仓库！", true, false);
            CommonUtil.requestFocusAndClearText(et_orderNo);
            return;
        }
        this.orderInfoBean = orderInfoBean;
        lists.clear();
        lists.addAll(orderInfoBean.getStockOutOrderDetailInfos());
        adapter.setOpinionPosition(-1);
        adapter.notifyDataSetChanged();

        reflushTextView();
    }


    @Override
    public void reviewStockOutBillOrExpressNoFailed(String msg) {
        SpeakUtils.speakWithToast(OutCheckActivity.this, msg, true, false);
        clearView();
    }

    @Override
    public void pdaSnScanSuccess(ScanSnResponsebean scanSnResponsebean) {
        //判断扫描的sn信息是否属于该仓库
        if (orderInfoBean != null && !TextUtils.equals(orderInfoBean.getWarehouseId() + "", scanSnResponsebean.getWarehouseid())) {
            SpeakUtils.speakWithToast(OutCheckActivity.this, "该SN不属于此仓库", true, false);
//            if (!isMidSnScan) {
            CommonUtil.requestFocusAndClearText(et_skuCode);
//            } else {
//                CommonUtil.requestFocusAndClearText(et_snCode);
//            }
            return;
        }
        skuCode = scanSnResponsebean.getSku();
        snScanPass(scanSnResponsebean);
        CommonUtil.requestFocusAndClearText(et_skuCode);
    }

    /**
     * 正常sn校验成功/半程唯一码校验不存在时调用
     *
     * @param scanSnResponsebean
     */
    private void snScanPass(ScanSnResponsebean scanSnResponsebean) {
        SpeakUtils.onlyRing(this, 2);
        int isExit = -1;//-1 条码不存在  0 存在但是数量超过  1存在并且数量可复核 2已扫描
        StockOutOrderDetailInfosBean detailInfosBean = null;
        int index = 0;
        for (int i = 0; i < lists.size(); i++) {
            StockOutOrderDetailInfosBean bean = lists.get(i);
            if (bean.getSku().equals(skuCode)) {
                detailInfosBean = bean;
                index = i;
                break;
            }
        }

        if (detailInfosBean != null) {
            switch (getSnType(detailInfosBean)) {
                case "ALL":
                    break;
                case "HALF":
                case "OFF":
                    SpeakUtils.speakWithToast(OutCheckActivity.this, "请扫描商品条码！", true, false);
                    CommonUtil.requestFocusAndClearText(et_skuCode);
                    return;
                default:
                    SpeakUtils.speakWithToast(OutCheckActivity.this, "类型不存在！", true, false);
                    CommonUtil.requestFocusAndClearText(et_skuCode);
                    return;
            }
            //如果该商品没开启SN，且扫描匹配通过，继续判断数量能否继续复核
            isExit = addSnData(detailInfosBean, scanSnResponsebean, index);
        }

        if (isExit == -1) {
            SpeakUtils.speakWithToast(OutCheckActivity.this, "商品不属于该出库单！", true, false);
        } else if (isExit == 0) {
            SpeakUtils.speakWithToast(OutCheckActivity.this, "商品已扫描数量不可超过该商品总数！", true, false);
        } else if (isExit == 2) {
            SpeakUtils.speakWithToast(OutCheckActivity.this, "此SN已扫描！", true, false);
        } else {
            floatbutton.setVisibility(View.VISIBLE);
        }
        scanSkuOrQrFinished();
    }

    /**
     * 将sn信息保存到请求对象中
     *
     * @param bean
     * @param scanSnResponsebean
     * @param i
     * @return
     */
    public int addSnData(StockOutOrderDetailInfosBean bean, ScanSnResponsebean scanSnResponsebean, int i) {
        int isExit = -1;//-1 条码不存在  0 存在但是数量超过  1存在并且数量可复核 2已扫描

        //判断
        boolean hasScan = false;
        a:
        for (SnlistBean snBean : bean.getSnlist()) {
//            if (isMidSnScan) {
            if (snBean.getSn().equals(et_snCode.getText().toString()) || snBean.getSn().equals(et_skuCode.getText().toString())) {
                hasScan = true;
                break a;
            }
//            } else {
//                if (snBean.getSn().equals(scanSnResponsebean.getSn())) {
//                    hasScan = true;
//                    break a;
//                }
//            }
        }

        if (hasScan) return 2;

        isExit = 0;
        if (bean.getScannedqty() != bean.getQty()) {
            isExit = 1;
            bean.setScannedqty(bean.getScannedqty() + 1);
            SnlistBean snlistBean;
            if (scanSnResponsebean == null) {
                snlistBean = new SnlistBean("0", et_snCode.getText().toString(), bean.getSkucode());
            } else {
                snlistBean = new SnlistBean(scanSnResponsebean.getId(), scanSnResponsebean.getSn(), bean.getSkucode());
            }
            Set<SnlistBean> snlists = bean.getSnlist();
            snlists.add(snlistBean);
            bean.setSnlist(snlists);
            adapter.setOpinionPosition(i);
            adapter.notifyDataSetChanged();

            scanSkuOrQrFinished();

            reflushTextView();
        }
        return isExit;
    }

    private void scanSkuOrQrFinished() {
        if (qrcode_isopen) {
            et_skuCode.setText("");
            et_snCode.setText("");
            CommonUtil.requestFocusAndClearText(et_specialCode);
        } else {
            CommonUtil.requestFocusAndClearText(et_skuCode);
            et_snCode.setText("");
        }
    }

    @Override
    public void pdaSnScanFailed(String msg) {
//        if (isMidSnScan) {
//            if ("该序列号不存在".equals(msg)) {
//                snScanPass(null);
//            } else {
        SpeakUtils.speakWithToast(OutCheckActivity.this, msg, false, false);
        scanSkuOrQrFinished();
//            }
//        } else {
//            SpeakUtils.speakWithToast(OutCheckActivity.this, msg, false, false);
//            CommonUtil.requestFocusAndClearText(et_skuCode);
//        }
    }

    @Override
    public void pdaCollectNullSnSuccess(ScanSnResponsebean orderInfoBean) {
        if (orderInfoBean != null) {
            SpeakUtils.speakWithToast(OutCheckActivity.this, "该序列号已经存在", false, false);
            et_snCode.setText("");
            CommonUtil.requestFocusAndClearText(et_snCode);
            return;
        }

        ScanSnResponsebean scanSnResponsebean = new ScanSnResponsebean();
        scanSnResponsebean.setOwner(selectDetailInfosBean.getOwner());
        scanSnResponsebean.setSku(selectDetailInfosBean.getSku());
        scanSnResponsebean.setOwnertype(selectDetailInfosBean.getOwnertype());
        scanSnResponsebean.setSn(et_snCode.getText().toString());
        int isExit = addSnData(selectDetailInfosBean, scanSnResponsebean, selectDetailInfosBeanIndex);
        if (isExit == -1) {
            SpeakUtils.speakWithToast(OutCheckActivity.this, "商品不属于该出库单！", true, false);
        } else if (isExit == 0) {
            SpeakUtils.speakWithToast(OutCheckActivity.this, "商品已扫描数量不可超过该商品总数！", true, false);
        } else if (isExit == 2) {
            SpeakUtils.speakWithToast(OutCheckActivity.this, "此SN已扫描！", true, false);
        } else {
            floatbutton.setVisibility(View.VISIBLE);
        }
        et_snCode.setEnabled(false);
        et_snCode.setText("");
        CommonUtil.requestFocusAndClearText(et_skuCode);
    }

    @Override
    public void pdaCollectNullSnFailed(String msg) {
        SpeakUtils.speakWithToast(OutCheckActivity.this, msg, false, false);
        et_snCode.setText("");
        CommonUtil.requestFocusAndClearText(et_snCode);
    }

    @Override
    public void confirmStockOutReviewResult(boolean isSuccess, String msg) {
        if (isSuccess) {
            SpeakUtils.onlyRing(this, 1);
            clearView();
            orderNum++;
            tv_orderNum.setText(orderNum + "");
        } else {
            CommonUtil.requestFocusAndClearText(et_skuCode);
            SpeakUtils.speakWithToast(OutCheckActivity.this, msg, true, false);
        }
    }

    @Override
    public void changeWarehouse(Warehouse warehouse) {

    }

    private void reflushTextView() {
        int allQty = 0;
        int checkedQty = 0;
        for (StockOutOrderDetailInfosBean bean : lists) {
            allQty += bean.getQty();
            checkedQty += bean.getScannedqty();
        }

        tv_skuNum.setText(allQty + "");
        tv_hasCheck.setText(checkedQty + "");
        tv_waitCheck.setText((allQty - checkedQty) + "");

        //自动提交复核
        if (allQty == checkedQty) {
            btn_confirm.setEnabled(true);
            outcheckConfirm();
        }
    }

    private void clearView() {
        et_skuCode.setText("");
        tv_skuNum.setText("-");
        tv_hasCheck.setText("-");
        tv_waitCheck.setText("-");

        et_specialCode.setText("");
        et_snCode.setText("");

        lists.clear();
        adapter.notifyDataSetChanged();
        CommonUtil.requestFocusAndClearText(et_orderNo);
        btn_confirm.setEnabled(false);

        floatbutton.setVisibility(View.GONE);
    }
}
